package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.result.GoldQryResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.base.GoldForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.OperateFundBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.BrokerFundListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.BrokerIncomeListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.BrokerIncomeListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.FansChargeListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.FansChargeListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.FansConsumeListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.FansConsumeListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.FansFundListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.DetailQueryListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.FansBranchQueryListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.FundFrozenForm;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.PayWater;
import com.cloudbroker.bcs.platform.dav.middle.entity.RechargeWater;
import com.cloudbroker.bcs.platform.dav.middle.entityexample.BrokerId;
import com.cloudbroker.bcs.platform.dav.middle.entityexample.CustomerId;
import com.cloudbroker.bcs.platform.dav.middle.entityview.BrokerFundListDataView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.FansFundListDataView;
import com.cloudbroker.bcs.platform.dav.middle.extservice.gold.GoldService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.PayWaterService;
import com.cloudbroker.bcs.platform.dav.middle.service.RechargeWaterService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.util.GoldTokenUtil;

/**
 * Created by wangxu13798 on 2016/8/17.
 */
@Service
public class OperateFundBizServiceImpl implements OperateFundBizService {

    @Resource
    TenantService tenantService;

    @Resource
    CustomerService customerService;

    @Resource
    BrokerService brokerService;

    @Resource
    PayWaterService payWaterService;

    @Resource
    RechargeWaterService rechargeWaterService;
    
    @Resource
    GoldService goldService;
    
    @Resource
    BrokerManagerService brokerManagerService;

    @Override
    public FansFundListResult funcFansFundList(FansBranchQueryListForm form) {
        boolean manager = managerJudge(form.getBranch_no());
        Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
        Integer pageCount = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        String keyword = StringUtil.isBlank(form.getKeyword()) ? null : form.getKeyword();
        FansFundListResult result = new FansFundListResult();
        List<FansFundListDataView> resultList = new ArrayList<>();

        //通过机构ID获取租户ID，根据租户ID获取粉丝数目，并分页获取粉丝信息
        List<Long> tenantIds = null;
        if (!manager) {
            tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
            if (tenantIds.isEmpty()) {
                return VOUtil.setSuccessResult(result);
            }
        }
        List<Customer> customers = customerService.getByTenants(keyword, tenantIds, (pageNo - 1) * pageCount,
                pageCount);
        Integer counts = customerService.countByTenants(keyword, tenantIds);
        List<Long> customerIds = new ArrayList<>();
        for (Customer customer : customers) {
            customerIds.add(customer.getCustomer_id());
        }
        //通过租户ID和粉丝ID获取粉丝消费和充值记录
        List<FansFundListDataView> payList = null;
        List<FansFundListDataView> rechargeList = null;
        if (!customers.isEmpty()) {
            payList = payWaterService.queryFundListByCustomer(customerIds, tenantIds);
            rechargeList = rechargeWaterService.queryFundListByCustomer(customerIds,
                    tenantIds);
        }

        //将从数据库获取的数据放到结果集中
        for (int i = 0; i < customers.size(); i++) {
            FansFundListDataView fansFundListDataView = new FansFundListDataView();
            fansFundListDataView.setCustomer_id(customers.get(i).getCustomer_id());
            fansFundListDataView.setCustomer_name(customers.get(i).getCustomer_name());
            fansFundListDataView.setMobile(customers.get(i).getMobile());
            fansFundListDataView.setTenant_id(customers.get(i).getTenant_id());
            fansFundListDataView.setFund_flag(customers.get(i).getFund_flag());
            GoldForm gform = new GoldForm();
            gform.setUser_id(customers.get(i).getCustomer_key());
            gform.setUser_token(GoldTokenUtil.getGoldToken());
            GoldQryResult backVo = goldService.userCurGoldQry(gform);
            if (!VOUtil.isSuccess(backVo)) {
                return VOUtil.genErrorResult(ClientErr.AMOUNT_QRY_FAIL, FansFundListResult.class);
            }
            if (!VOUtil.isSuccess(backVo)) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.AMOUNT_QRY_FAIL, FansFundListResult.class);
            }
            BigDecimal amount = ValueUtil.getBigDecimal(backVo.getCurrent_amount());
            fansFundListDataView.setAccount_balance(amount.doubleValue() / 10);
            for (int j = 0; j < payList.size(); j++) {
                if (payList.get(j).getCustomer_id().equals(customers.get(i).getCustomer_id())) {
                    fansFundListDataView.setConsume_num(payList.get(j).getConsume_num());
                    fansFundListDataView.setConsume_amount(payList.get(j).getConsume_amount());
                    String date = payList.get(j).getConsume_time();
                    if (date != null && !date.isEmpty()) {
                        fansFundListDataView.setConsume_time(date.substring(0, date.length() - 2));
                    }
                    break;
                }
            }
            for (int j = 0; j < rechargeList.size(); j++) {
                if (rechargeList.get(j).getCustomer_id().equals(customers.get(i).getCustomer_id())) {
                    fansFundListDataView.setCharge_num(rechargeList.get(j).getCharge_num());
                    fansFundListDataView.setCharge_amount(rechargeList.get(j).getCharge_amount());
                    break;
                }
            }
            resultList.add(fansFundListDataView);
        }

        result.setPage_no(pageNo);
        result.setRecord_count(counts);
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public BrokerFundListResult funcBrokerFundList(FansBranchQueryListForm form) {
        boolean manager = managerJudge(form.getBranch_no());
        Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
        Integer pageCount = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        String keyword = StringUtil.isBlank(form.getKeyword()) ? null : form.getKeyword();
        BrokerFundListResult result = new BrokerFundListResult();
        List<BrokerFundListDataView> resultList = new ArrayList<>();

        //通过机构ID获取租户ID，根据租户ID获取投顾数目，并分页获取投顾信息
        List<Long> tenantIds = null;
        if (!manager) {
            tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
            if (tenantIds.isEmpty()) {
                return VOUtil.setSuccessResult(result);
            }
        }
        List<Broker> brokers = brokerService.getByTenants(keyword, tenantIds, (pageNo - 1) * pageCount, pageCount);
        Integer counts = brokerService.countByTenants(keyword, tenantIds);
        List<Long> brokerIds = new ArrayList<>();
        for (Broker broker : brokers) {
            brokerIds.add(broker.getBroker_id());
        }
        //通过租户ID和投顾ID获取投顾收入记录
        List<BrokerFundListDataView> payList = null;
        if (!brokers.isEmpty()) {
            payList = payWaterService.queryFundListByBroker(brokerIds, tenantIds);
        }

        //将从数据库获取的数据放到结果集中
        for (int i = 0; i < brokers.size(); i++) {
            BrokerFundListDataView brokerFundListDataView = new BrokerFundListDataView();
            brokerFundListDataView.setBroker_id(brokers.get(i).getBroker_id());
            brokerFundListDataView.setBroker_name(brokers.get(i).getBroker_name());
            brokerFundListDataView.setMobile(brokers.get(i).getMobile());
            brokerFundListDataView.setTenant_id(brokers.get(i).getTenant_id());
            brokerFundListDataView.setFund_flag(brokers.get(i).getFund_flag());
            GoldForm gform = new GoldForm();
            gform.setUser_id(brokers.get(i).getBroker_key());
            gform.setUser_token(GoldTokenUtil.getGoldToken());
            GoldQryResult backVo = goldService.userCurGoldQry(gform);
            if (!VOUtil.isSuccess(backVo)) {
                return VOUtil
                        .genErrorResult(HSBCPSErrorCodes.ClientErr.AMOUNT_QRY_FAIL, BrokerFundListResult.class);
            }
            BigDecimal amount = ValueUtil.getBigDecimal(backVo.getCurrent_amount());
            brokerFundListDataView.setAccount_balance(amount.doubleValue() / 10);
            for (int j = 0; j < payList.size(); j++) {
                if (payList.get(j).getBroker_id().equals(brokers.get(i).getBroker_id())) {
                    brokerFundListDataView.setIncome_num(payList.get(j).getIncome_num());
                    brokerFundListDataView.setIncome_amount(payList.get(j).getIncome_amount());
                    break;
                }
            }
            resultList.add(brokerFundListDataView);
        }

        result.setPage_no(pageNo);
        result.setRecord_count(counts);
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public FansConsumeListResult funcFansConsumeList(DetailQueryListForm form) {
        FansConsumeListResult result = new FansConsumeListResult();
        List<FansConsumeListData> resultList = new ArrayList<>();
        Long customerId = ValueUtil.getLong(form.getDetail_id());
        Integer tenantId = ValueUtil.getInt(form.getTenant_id());
        Integer requestNum = ValueUtil.getInt(form.getRequest_num());
        Customer cusomter = customerService.getById(customerId, tenantId);
        if (cusomter == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, FansConsumeListResult.class);
        }
        List<PayWater> payWaters = payWaterService.getByCustomer(customerId, tenantId, form.getPosition_str(),
                requestNum);
        for (PayWater payWater : payWaters) {
            FansConsumeListData fansConsumeListData = new FansConsumeListData();
            fansConsumeListData.setCustomer_name(cusomter.getCustomer_name());
            fansConsumeListData.setPosition_str(payWater.getPosition_str());
            fansConsumeListData.setConsume_type(payWater.getPay_source());
            fansConsumeListData.setConsume_amount(payWater.getReal_pay_balance());
            fansConsumeListData.setConsume_time(DateTimeUtil.toString(payWater.getCreate_time(),
                    DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
            resultList.add(fansConsumeListData);
        }
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public FansChargeListResult funcFansChargeList(DetailQueryListForm form) {
        FansChargeListResult result = new FansChargeListResult();
        List<FansChargeListData> resultList = new ArrayList<>();
        Long customerId = ValueUtil.getLong(form.getDetail_id());
        Integer tenantId = ValueUtil.getInt(form.getTenant_id());
        Integer requestNum = ValueUtil.getInt(form.getRequest_num());
        Customer cusomter = customerService.getById(customerId, tenantId);
        if (cusomter == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, FansChargeListResult.class);
        }
        List<RechargeWater> payWaters = rechargeWaterService.getByCustomer(customerId, tenantId,
                form.getPosition_str(), requestNum);
        for (RechargeWater rechargeWater : payWaters) {
            FansChargeListData fansChargeListData = new FansChargeListData();
            fansChargeListData.setCustomer_name(cusomter.getCustomer_name());
            fansChargeListData.setPosition_str(rechargeWater.getPosition_str());
            fansChargeListData.setCharge_amount(ValueUtil.getDouble(rechargeWater.getRecharge_amount()));
            fansChargeListData.setCharge_time(DateTimeUtil.toString(rechargeWater.getCreate_time(),
                    DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
            resultList.add(fansChargeListData);
        }
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public BrokerIncomeListResult funcBrokerIncomeList(DetailQueryListForm form) {
        BrokerIncomeListResult result = new BrokerIncomeListResult();
        List<BrokerIncomeListData> resultList = new ArrayList<>();
        Long brokerId = ValueUtil.getLong(form.getDetail_id());
        Integer tenantId = ValueUtil.getInt(form.getTenant_id());
        Integer requestNum = ValueUtil.getInt(form.getRequest_num());
        Broker broker = brokerService.getById(brokerId, tenantId);
        if (broker == null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, BrokerIncomeListResult.class);
        }
        List<PayWater> payWaters = payWaterService.getByBroker(brokerId, tenantId, form.getPosition_str(),
                requestNum);
        for (PayWater payWater : payWaters) {
            BrokerIncomeListData brokerIncomeListData = new BrokerIncomeListData();
            brokerIncomeListData.setBroker_name(broker.getBroker_name());
            brokerIncomeListData.setPosition_str(payWater.getPosition_str());
            brokerIncomeListData.setIncome_type(payWater.getPay_source());
            brokerIncomeListData.setIncome_amount(payWater.getReal_pay_balance());
            brokerIncomeListData.setIncome_time(DateTimeUtil.toString(payWater.getCreate_time(),
                    DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
            resultList.add(brokerIncomeListData);
        }
        result.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public HSBCPSBackVO funcFansFundFrozen(FundFrozenForm form) {
        String customerId = form.getFund_frozen_id();
        JSONArray jsonArray = JSONUtil.toJsonArray(customerId);
        List<CustomerId> customers = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            CustomerId customerid = new CustomerId();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            customerid.setCustomer_id(jsonObject.getLong("customer_id"));
            customerid.setTenant_id(jsonObject.getInteger("tenant_id"));
            customers.add(customerid);
        }
        Integer counts = customerService.countByIds(customers);
        if (!counts.equals(customers.size())) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ClientErr.FROZEN_ID_ERROR);
        }
        customerService.updateByIds(customers, form.getFund_flag());
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public HSBCPSBackVO funcBrokerFundFrozen(FundFrozenForm form) {
        String brokerId = form.getFund_frozen_id();
        JSONArray jsonArray = JSONUtil.toJsonArray(brokerId);
        List<BrokerId> brokers = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            BrokerId brokerid = new BrokerId();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            brokerid.setBroker_id(jsonObject.getLong("broker_id"));
            brokerid.setTenant_id(jsonObject.getInteger("tenant_id"));
            brokers.add(brokerid);
        }
        Integer counts = brokerService.countByIds(brokers);
        if (!counts.equals(brokers.size())) {
            return VOUtil.genErrorResultVo(HSBCPSErrorCodes.ClientErr.FROZEN_ID_ERROR);
        }
        brokerService.updateByIds(brokers, form.getFund_flag());
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public HSBCPSBackVO funcOperateConnectTest(HSBCPSVO form) {
        return VOUtil.genSuccessBackVo();
    }

    private boolean managerJudge(String branchNo) {
        String[] branchSplit = branchNo.split(",");
        for (int i = 0; i < branchSplit.length; i++) {
            if (ConfigValues.getYunjiBranchNo().equals(branchSplit[i])) {
                return true;
            }
        }
        return false;
    }
}